package net.zisen.cloud.goods.service;

import com.codingapi.txlcn.tc.annotation.LcnTransaction;
import net.zisen.cloud.base.msg.ResultMsg;
import net.zisen.cloud.goods.model.Goods;
import org.beetl.sql.core.SQLManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
 * @author tim/278002989@qq.com
 * @Classname GoodsServiceImpl
 * @Description TODO
 * @Date 2019-05-17 17:26
 */
@Service
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    private SQLManager sqlManager;

    /**
     * 获取商品
     *
     * @param goodsId
     * @return
     */
    @Override
    public Goods getById(Long goodsId) {
        return sqlManager.single(Goods.class, goodsId);
    }

    /**
     * 更新商品库存
     *
     * @param goodsId
     * @param quality
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class, timeout = 60, isolation = Isolation.READ_COMMITTED)
    @LcnTransaction
    public ResultMsg updateQuality(Long goodsId, Integer quality) {
        Goods goods = sqlManager.single(Goods.class, goodsId);
        if (!Optional.of(goods).isPresent() && !goods.getState().equals(Goods.State.IN_SALE.value())) {
            return ResultMsg.fail().resultMsg("未找到商品，或商品下架！");
        }
        if (goods.getQuality() < quality) {
            return ResultMsg.fail().resultMsg("库存不足！");
        }
        goods.setQuality(goods.getQuality() - quality);
        this.sqlManager.updateById(goods);
        return ResultMsg.ok().resultMsg("更新库存成功");
    }
}
